package com.jbookshelf.dal.providers;

import java.util.LinkedList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Expression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jbookshelf.dal.entities.Publishers;

@Repository
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public class PublishersDataProviderImp implements PublishersDataProvider{

	@Autowired
	SessionFactory sessionFactory;
	
	@Override
	@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
	public List<Publishers> getPublishers() {
		Session s = sessionFactory.getCurrentSession();
		Query q  = s.createQuery("from Publishers p " );
        List<Publishers> list = q.list();
		return list;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void setPublisher(Publishers publisher) {
        Session s = sessionFactory.getCurrentSession();
        s.save(publisher);
		
	}

    @Override
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void updatePubliser( Publishers publishers ) {
        Session s = sessionFactory.getCurrentSession();
        s.update(publishers);
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public boolean validatePublisher(Publishers publishers) {
        List<Publishers> publishersList;
        try{
            Session session = sessionFactory.getCurrentSession();
            Criteria criteria = session.createCriteria(Publishers.class);
            publishersList = criteria.add(Expression.like("name", publishers.getName())).list();
        }catch (Exception e){
              publishersList = new LinkedList<Publishers>();
        }

        if (publishersList.isEmpty()) return true;
            else return false;
    }

}
